import universalBehavior from '../../../behavior/universalBehavior'
import { useRequest } from "../../../utils/request";

const WeValidator = require('../../../package/we-validator.min')

Component({
    behaviors: [universalBehavior],
    properties: {},
    data: {
        phone: ''
    },
    methods: {
        onLoad() {
            this.reset = new useRequest('api/resetpassd', {
                hold: true
            }, this)
            this.getCode = new useRequest('api/verifycode', {
                hold: true,
                loading: 'codeLoading'
            }, this)

            this.validatorInstance = new WeValidator({
                rules: {
                    phone: {
                        required: true,
                        mobile: true
                    },
                    code: {
                        required: true,
                    },
                    password: {
                        required: true,
                    }
                },
                messages: {
                    phone: {
                        required: '请输入手机号',
                        mobile: '请输入正确的手机号'
                    },
                    code: {
                        required: '请输入验证码',
                    },
                    password: {
                        required: '请输入密码',
                    }
                },
            })
        },

        startTimeout() {
            this.setData({
                second: 59
            })
            this.timeout = setInterval(() => {
                this.setData({
                    second: this.data.second - 1
                })
                if (this.data.second <= 0) {
                    clearInterval(this.timeout)
                }
            }, 1000)
        },

        getPhoneCode() {
            if (
                WeValidator.checkValue('required', this.data.phone) &&
                WeValidator.checkValue('mobile', this.data.phone, true)
            ) {
                this.getCode.run({ phone: this.data.phone }).then(() => {
                    this.startTimeout()
                })
            }
        },

        submit(e) {
            const value = e.detail.value

            if (this.validatorInstance.checkData(value)) {
                this.reset.run(value).then(() => {
                    wx.showToast({
                        title: '修改成功',
                        success() {
                            wx.navigateBack()
                        }
                    })
                })
            }
        },
    }
})
